package cn.ant.utils;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
 * 创建信道的工具类
 * @author Anhui AntLaddie <a href="https://juejin.cn/user/4092805620185316">(掘金蚂蚁小哥)</a>
 * @version 1.0
 **/
public class ChannelUtil {

    private static final String HOST = "111.231.171.158";       // 服务器IP
    private static final String USER_NAME = "rabbit";           // 用户信息
    private static final String PASSWORD = "1234";              // 用户密码
    private static final String VIRTUAL_HOST = "nativeStudy";   // 虚拟主机

    /***
     * 获取连接中的一个信道
     * @return Channel
     */
    public static Channel getChannel() {
        //创建一个连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //设置RabbitMQ服务的IP、账号、密码、Vhost虚拟主机(默认 "/" 则不需要设置)
        factory.setHost(HOST);
        factory.setUsername(USER_NAME);
        factory.setPassword(PASSWORD);
        factory.setVirtualHost(VIRTUAL_HOST);

        try {
            //通过工厂对象获取一个连接
            Connection connection = factory.newConnection();
            //通过连接来获取一个信道并返回
            return connection.createChannel();
        } catch (IOException | TimeoutException e) {
            throw new RuntimeException(e);
        }
    }
}
